﻿var CityValidationClientSideHide = false;
var PageNumber = 1;
var IsSearchView = false;
var CityIDView = 0;
var IsDeleteView = false;
var CityComElem = null;
var CityComElemVal = null;
var CityTimerId = null;
$(document).ready(function () {
    var path = window.location.pathname;
    if (path.indexOf("SetupCity") != -1) {
        $.validator.addMethod("SetupCityRequireds", $.validator.methods.required, Messages["SetupCityRequireds"]);
        $.validator.addMethod("SetupCityMaxLength30", $.validator.methods.maxlength, Messages["SetupCityMaxLength30"]);
        $.validator.addClassRules({
            Required: {
                SetupCityRequireds: true,
            },
            MaxLength30: {
                SetupCityMaxLength30: 30,
            },
        });

        $('#LoadCityDetailsForm').validate();
        LoadCityGrid();
    }
});
$(document).on('change', '.ChangedCityElements', function () {
    $('#CityDetailsSaveBtn').addClass('BackColorRed');
});
$(document).on('change', '.CityAddElementChange', function () {
    $('#CityAddBtn').addClass('BackColorRed');
});
function DeleteCity(CityID) {
    jConfirm('Are you sure you want to delete this City?', 'Warning!', function (retVal) {
        if (retVal == true) {
            CityIDView = CityID;
            IsDeleteView = true;
            LoadCityGrid();
        }
    });
}
function AddNewCity() {
    CityValidationClientSideHide = false;
    $.ajax({
        url: urls["SetupAddNewCity"],
        type: 'GET',
        success: function (data) {
            $("#AddNewCityDiv").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            IsDeleteView = false;
            AddNewCityPopUp("AddNewCityDiv");
        }
    });
}
$(document).on('click', '#CityMoreBtn', function () {
    PageNumber = PageNumber + 1;
    IsDeleteView = false;
    LoadCityGrid();
});
$(document).on('click', '#CitySearchBtn', function () {
    IsSearchView = true;
    IsDeleteView = false;
    LoadCityGrid();
});
function AddNewCityPopUp(PopUpDiv) {
    $.colorbox({
        width: "600px",
        height: "245px",
        inline: true,
        href: "#" + PopUpDiv,
        onComplete: function () {
            $("#" + PopUpDiv).show();
        },
        onClosed: function () {
            $("#" + PopUpDiv).hide();
        }
    });
}
$(document).on('click', '#CityAddBtn', function () {
    var $form = $('#AddNewCityForm');
    if ($form.valid()) {
        CityValidationClientSideHide = false;
        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
            data: $form.serialize(),
            beforeSend: function (xhr) {
                xhr.overrideMimeType('text/plain; charset=x-user-defined');
            },
            success: function (data) {
                if (data.indexOf("Error") != -1)
                    jAlert(data, "Error");
            },
            error: function (xhr) {
                jAlert(xhr.statusText, "Error");
            },
            complete: function () {
                $('#CityAddBtn').removeClass('BackColorRed')
                jAlert("Data SuccessFully Saved:", "Successful");
                $('#cboxClose').click();
                IsDeleteView = false;
                LoadCityGrid();
            }
        });
    }
    else
        CityValidationClientSideHide = true;
});

$(document).on('click', '#CityDetailsSaveBtn', function () {
        var $form = $('#LoadCityDetailsForm');
        if ($form.valid()) {
            if ($form[0].length > 0) {
                $.ajax({
                    url: $form.attr('action'),
                    type: $form.attr('method'),
                    data: $form.serialize(),
                    beforeSend: function (xhr) {
                        xhr.overrideMimeType('text/plain; charset=x-user-defined');
                    },
                    success: function (data) {
                        if (data.indexOf("Error") != -1)
                            jAlert(data, "Error");
                    },
                    error: function (xhr) {
                        jAlert(xhr.statusText, "Error");
                    },
                    complete: function () {
                        $('#CityDetailsSaveBtn').removeClass('BackColorRed')
                        jAlert("Data SuccessFully Saved:", "Successful");
                        IsDeleteView = false;
                        LoadCityGrid();
                    }
                });
            }
            else
                jAlert("You have not data to save:", "Attention!");
        }
});

$(document).on('change', '.CountrySearch', function () {
    if ($("#SelectedCountryText").val() == "1") {
        $(".StateToHideLabel").show();
        $(".StateToHideDrop").show();
    }
    else {
        $(".StateToHideLabel").hide();
        $(".StateToHideDrop").hide();
    }
});
function LoadCityGrid() {
    var StateSearchText = "";
    if ($("#SelectedCountryText").val() == "1")
    {
        StateSearchText = $("#SelectedStateText").val();
    }
    var SetupCitiesGridViewModel = {
        CityText: $("#CityText").val(),
        SelectedCountryText: $("#SelectedCountryText").val(),
        SelectedStateText: StateSearchText,
        PageNum: parseInt(PageNumber),
        IsSearch: IsSearchView,
        IsDelete: IsDeleteView,
        CityID: parseInt(CityIDView),
        IsActiveSearch: $("#IsActiveSearch").val(),
    };

    var DTO = JSON.stringify(SetupCitiesGridViewModel);
    $.ajax({
        url: urls["SetupLoadCitiesGrid"],
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: DTO,
        success: function (data) {
            $("#SetupCityGrid").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            BindCityCountryDrop();
            BindCityStateDrop;
        }
    });
}
// text element complete text 
$(document).on('input', '.QuotaTxtComplete', function () {
    if (CityTimerId == null) {
        CityComElem = $(this).attr('id');
        CityComElemVal = $("#" + CityComElem).val();
        CityTimerId = setInterval(function () {

            var keyword = $("#" + CityComElem).val();
            if (keyword == CityComElemVal) {
                var PropName = "";
                if (CityComElem.indexOf("CityText") != -1)
                    PropName = "CityText";

                var position = $("#" + CityComElem).offset();
                position.top = position.top + $("#" + CityComElem).height() + 5;
                $.ajax({
                    url: urls["SetupAutoComplete"],
                    data: { 'PropName': PropName, 'keyword': keyword },
                    type: 'POST',
                    success: function (data) {
                        $("#AutoCompleteDiv").html(data);
                        var width = $("#" + CityComElem).css("width");
                        $("#AutoCompleteDiv").css("width", width);
                        $("#AutoCompleteDiv").show();
                        $("#AutoCompleteDiv").offset(position);
                    },
                    error: function (xhr) {
                        jAlert(xhr.statusText, "Error");
                    },
                    complete: function () {
                        clearInterval(CityTimerId);
                        CityTimerId = null;
                    }
                });
            }
            else
                CityComElemVal = keyword;
        }, 600);
    }
});
$(document).on('click', '.QuotaAutoCompleteDivClose', function () {
    $(this).parent().parent().hide();
});
function htmlDecode(value) {
    return $('<div/>').html(value).text();
}
function AutoCompleteRowClick(key, val) {
    val = htmlDecode(val);
    $("#" + CityComElem).val(val);
    if (CityComElem.indexOf("CityText") != -1)
        $("#" + CityComElem).next().val(key);
    $("#AutoCompleteDiv").hide();
}
$(document).on('change', '.CountryDrop', function () {
    if ($(this).val() === '1') {
        $.ajax({
            url: urls["SetupGetStateByCountryID"],
            data: { CountryID: parseInt($(this).val()) },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value='0'>Select</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $("Select.StateDrop").html(markup);
            },
            error: function (reponse) {
                jAlert(reponse, "Error");
            },
            complete: function () {
                $("#SelectedStateID").addClass('Required');
                $("#StateDiv").show();
                $("#StateDivChange").hide();
            }
        });
    }
    else {
        $("#SelectedStateID").removeClass('Required');
        $("#StateDiv").hide();
        $("#StateDivChange").show();
    }
});
function BindCityCountryDrop() {
    $(".CityCountryDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
    });
}
$(document).on('change', '.CityCountryDrop', function () {
    if ($(this).val() === '1') {
        $(this).parent().parent().find("Select.GridStateDrop").show();
        $(this).parent().parent().find("Select.CityStateDrop").prop("selectedIndex", 0);
        BindCityStateDrop();
    }
    else {
        $(this).parent().parent().find("Select.GridStateDrop").hide();
    }
    $(".CityCountryDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
    });
});
function BindCityStateDrop() {
    $(".CityStateDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
    });
}
$(document).on('change', '.CityStateDrop', function () {
    $(".CityStateDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
    });
});


var originalClose = $.colorbox.close;
$.colorbox.close = function () {
    if ($('#CityAddBtn').hasClass('BackColorRed')) {
        jConfirm(Messages["ClosePopUp"], Messages["ClosePopUpTitle"], function (retVal) {
            if (retVal == true) {
                $("#AddNewCityForm").empty();
                LoadCityGrid();
                originalClose();
            }
        });
    }
    else {
        $("#AddNewCityForm").empty();
        LoadCityGrid();
        originalClose();
    }
};
$(document).on('change', '.ElementsForValidation', function () {
    if ($(this).valid()) {
        $(this).closest("form").find("#errorMessageClient").text("");
    }
    else
        $(this).closest("form").find("#errorMessageServer").hide();
    if (CityValidationClientSideHide) {
        if ($(this).closest("form").valid()) {
            $(this).closest("form").find("#errorMessageClient").text("");
        }
    }
    else if ($(this).valid()) {
        var elements = "#" + $(this).closest("form").attr("id") + " .error";
        $(elements).not('label').each(function () {
            $(this).valid();
        });
    }
});
$(document).on('change', '.ForValidation', function () {
    if ($(this).valid)
        $(this).removeClass('table_inputs_Unvalidated');
    if ($(this).closest("form").valid()) {
        $(this).closest("form").find("#errorMessageClient").text("");
        var elements = "#" + $(this).closest("form").attr("id") + " .error";
        $(elements).not('label').each(function () {
            if ($(this).valid())
                $(this).removeClass('table_inputs_Unvalidated');
        });
    }
    else
        $(this).closest("form").find("#errorMessageServer").hide();
});
